package com.zuo.seckilldemo.handler;

import com.zuo.seckilldemo.result.CodeMsg;
import com.zuo.seckilldemo.result.Result;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;



@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e){
        if (e instanceof GlobalException){
            GlobalException ex = (GlobalException) e;
            return Result.error(ex.getCodeMsg());
        }
        else if (e instanceof BindException){
            BindException ex = (BindException) e;

            Result<Object> result = Result.error(CodeMsg.BIND_ERROR);
            result.setMsg("参数校验异常 "+ ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        System.out.println(e.getMessage());
        e.printStackTrace();
        return Result.error(CodeMsg.SERVER_ERROR);
    }
}
